<?php

namespace App\Http\Controllers\Home;

use App\Model\Article;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ArticleController extends Controller
{
    public function __construct ()
    {
        //除了index、show方法不需要登录
        $this->middleware ( 'auth' , [ 'except' => [ 'index' , 'show' ] ] );
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $articles = Article::orderBy('id', 'desc')->paginate(10);

        return view('home.article.index',compact('articles'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('home.article.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
//        dd($request->all());
        $article = auth()->user()->article()->create($request->all());
        return redirect(route('article.show',$article))->with('success','文章发布成功');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Article $article)
    {
        //用户是否点赞
//        $isZan = $article->zan()->get()->contains( auth()->user() );
        //通过多态关联 获取用户点赞的文章
//        $users = $article->zan()->get();

        return view('home.article.show',compact('article'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Article $article)
    {
        $this->authorize('update',$article);

        return view('home.article.edit',compact('article'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Article $article)
    {
//        dd($article->toArray());
        $this->authorize('update',$article);

         $article->update($request->all());
        return redirect()->route('article.show',$article)->with('success','编辑成功');

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Article $article)
    {
        //
        $this->authorize('delete',$article);
        $article->delete();
        return redirect()->route('article.index')->with('success','删除成功');

    }

//    文章点赞
    public function TogoZan(Article $article){

//        dd($article->user_id);
        $this->authorize('isZanSub',$article);
        $article->zan()->toggle(auth()->id());

        return back()->with('操作成功');
    }
}
